package org.dbutils.dao.impl;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.dbutils.dao.StaffDao;
import org.dbutils.entity.Staff;
import org.dbutils.util.DruidUtil;

import java.sql.SQLException;
import java.util.List;

/**
 * @author CSY
 * @date 2025 - 02 - 25
 */
public class StaffDaoImpl4DbUtils implements StaffDao {
    //定义DbUtil类的执行器
    QueryRunner qr = new QueryRunner(DruidUtil.getDataSource());
    @Override
    public int insert(Staff staff) {
        // 定义要操作的sql语句
        String sql = "insert into staffs(name,age,phone,sta_pos) values (?,?,?,?);";
        //执行sql语
        try {
            return qr.update(sql,staff.getName(),staff.getAge(),staff.getPhone(),staff.getStaPos());
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public int update(Staff staff) {
        String sql = "update staffs set name=?,age=?,phone=?,sta_pos=? where id=?";
        try {
            return qr.update(sql,staff.getName(),staff.getAge(),staff.getPhone(),staff.getStaPos(),staff.getId());
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public int delete(int id) {
        String sql = "delete from staffs where id = ?";
        try {
            return qr.update(sql,id);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public List<Staff> selectByPage(int currentPage, int pageSize) {
        String sql = "select id,name,age,phone,sta_pos as staPos,add_time as addTime,update_time as updateTime from staffs limit ?,?";
        ResultSetHandler<List<Staff>> rsh = new BeanListHandler<>(Staff.class);
        try {
            return qr.query(sql, new BeanListHandler<>(Staff.class),(currentPage - 1) * pageSize,pageSize);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public Staff selectById(int id) {
        String sql = "select id,name,age,phone,sta_pos as staPos,add_time as addTime,update_time as updateTime from staffs where id = ?";
        try {
            return qr.query(sql, new BeanHandler<>(Staff.class),id);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
